package com.lwj.test.txt;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OperateTxt {
	
	public String filepath;
	public FileWriter fw = null;
	
	public OperateTxt(String filepath) {
		this.filepath = filepath;
		init();
	}

	public void init(){
		File file = new File(filepath);
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			fw = new FileWriter(filepath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void WriteTxt(String rowData) throws Exception{
		try {
			fw.write(rowData);
		} catch (IOException e) {
			//e.printStackTrace();
			throw new IOException(e.getMessage());
		}
	}
	
	public BufferedReader ReadTxtLine() throws Exception{
		FileReader read = null;
		try {
			read = new FileReader(filepath);
		} catch (FileNotFoundException e) {
			//e.printStackTrace();
			throw new Exception(e.getCause());
		}
		BufferedReader br = new BufferedReader(read);
		return br;
	}
	
	public List<String> ReadTxtToList() throws Exception{
		FileReader read = new FileReader(filepath);
		BufferedReader br = new BufferedReader(read);
		List<String> list = new ArrayList<String>();
		while (br.readLine()!=null) {
			list.add(br.readLine());
		}
		return list;
	}
	public void close(){
		try {
			fw.flush();
			fw.close();
		} catch (IOException e) {
			//e.printStackTrace();
		}
	}
}
